package com.validator;

import com.vo.AddressVo;
import com.vo.CustomerVo;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.Objects;

public class CustomerValidator implements Validator {

    private final Validator addressValidator;

    public CustomerValidator(Validator addressValidator) {
        this.addressValidator = Objects.requireNonNull(addressValidator);

        if (!addressValidator.supports(AddressVo.class)) {
            throw new IllegalArgumentException("校验器不支持 AddressVo 对象");
        }
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return CustomerVo.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "name", "客户名称不能为空");
        ValidationUtils.rejectIfEmpty(errors, "age", "年龄不能为空");

        final CustomerVo customer = (CustomerVo) target;

        try {
            errors.pushNestedPath("address");
            addressValidator.validate(customer.getAddress(),errors);
        }finally {
            errors.popNestedPath();
        }

    }
}
